package com.hjh.usb.accessory

import android.content.Intent
import android.hardware.usb.UsbAccessory
import android.hardware.usb.UsbManager
import android.os.Binder
import android.os.Environment
import android.os.IBinder
import com.hjh.core.service.BaseForegroundService
import com.hjh.usb.accessory.communication.AOAConnectionManager
import com.hjq.toast.Toaster
import kotlinx.coroutines.launch
import java.io.File

class AOAService : BaseForegroundService() {
    private lateinit var usbManager: UsbManager
    // private var communicationHelper: AOACommunicationHelper? = null
    private var communicationManager: AOAConnectionManager? = null

    override fun onBind(intent: Intent?): IBinder? = LocalBinder()

    override fun init() {
        usbManager = getSystemService(USB_SERVICE) as UsbManager
        // communicationHelper = AOACommunicationHelper(usbManager, serviceScope)
        communicationManager = AOAConnectionManager(usbManager, serviceScope)
        startForegroundNotification("AOAService", "AOAService", "AOA服务", "AOA服务运行中...")
    }

    override fun stop() {
        disconnect()
    }


    // 发送文件（通过AOA协议）
    fun sendFile(filePath: String, onResult: (Boolean) -> Unit) {
        val file = File(Environment.getExternalStorageDirectory(), filePath)
        if (!file.exists()) {
            Toaster.show("文件不存在")
            onResult(false)
            return
        }
        serviceScope.launch {
            // val success = communicationManager?.sender?.sendFile(file) == true
            val success = communicationManager?.communicator?.sendFile(file) == true
            onResult(success)
        }
    }

    // 连接USB设备
    fun connectAccessory(accessory: UsbAccessory) {
        // communicationHelper?.connect(accessory)
        communicationManager?.connect(accessory)
    }

    fun disconnect() {
        // communicationHelper?.disconnect()
        communicationManager?.disconnect()
    }

    inner class LocalBinder : Binder() {
        fun getService(): AOAService = this@AOAService
    }
}